package cn.hxzy.springbootredis;

import cn.hxzy.springbootredis.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class UserRedis {
    @Autowired
    RedisTemplate redisTemplate;

    String projectName="springboot-redis";

    /**
     * 清空项目全部缓存
     */
    public  void deleteAll() {
        String keys = projectName + "_*";
        Set deleteKeys = redisTemplate.keys(keys);
        for (Object deleteKey : deleteKeys) {
            redisTemplate.delete(deleteKey);
        }
    }

    /**
    * 设置值
    * @param key   键
    * @param user 值
    */
    public  void put(String key, User user) {
        String keys = projectName + "_" + key;
        redisTemplate.opsForValue().set(keys, user);
    }



    /**
    * 获取值
    * @param key 键
    * @return 值
    */
    public  User get(String key) {
        String keys = projectName + "_" + key;
        Object o = redisTemplate.opsForValue().get(keys);
        return (User) o;
    }


    /**
     * 删除键
     * @param key 键
     */
    public  void delete(String key) {
        String keys = projectName + "_" + key;
        redisTemplate.delete(keys);
    }

    /**
     * 设置键的过期时间
     * @param key      键
     * @param time     时间
     * @param timeUnit 单位
     */
    public  void expire(String key, long time, TimeUnit timeUnit) {
        String keys = projectName + "_" + key;
        redisTemplate.expire(keys, time, timeUnit);
    }



}